<template>
  <div class="p-15 p-t-0">
    <div class="table-padding orderDialog">
      <el-form :model="modelForm" ref="modelForm">
        <div>
          <el-row :gutter="24">
            <el-col :span="7">
              <el-form-item prop="supplier" :rules="[]" style="margin-right: 82px">
                <div class="el-input el-input-group el-input-group--prepend">
                  <div class="el-input-group__prepend">供应商</div>
                  <el-select v-model="modelForm.supplierId" :disabled="isEdit" filterable placeholder="请选择供应商" size="medium"
                             class="w-100p">
                    <el-option
                      v-for="item in suppliers"
                      :key="item.id"
                      :label="item.name"
                      :disabled="item.state && item.state.key!='NORMAL'"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item prop="warehouse" :rules="[]">
                <div class="el-input el-input-group el-input-group--prepend">
                  <div class="el-input-group__prepend">入库仓库</div>
                  <el-select v-model="modelForm.warehouseId" placeholder="请选择入库仓库" :disabled="isEdit" class="w-100p" size="medium">
                    <el-option
                      v-for="item in warehouses"
                      :key="item.id"
                      :disabled="item.state&& item.state.key!='NORMAL'"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8" >
              <el-form-item prop="createAt" :rules="[]">
                <div class="el-input el-input-group el-input-group--prepend">
                  <div class="el-input-group__prepend">入库日期</div>
                  <el-date-picker
                    v-model="modelForm.inTime"
                    type="date"
                    class="w-100p"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    :readonly="true"
                    placeholder="选择入库日期" >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row :gutter="24">
            <el-col :span="7">
              <div class="el-input el-input-group el-input-group--prepend addprepend el-input--medium"  v-if="$route.query.type==5" ><!--&& modelForm.type=='SHOUHUOIN'-->
                <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
                  <span>单据类型</span>
                </div>
                <div class="radio-group "  style="width: 40%;color:#888;line-height: 15px;">
                  <span v-if="modelForm.type=='STOREIN'">采购入库</span>
                  <span v-if="modelForm.type=='FANJIEIN'">反结算入库</span>
                  <span v-if="modelForm.type=='YICHUIN'">溢出入库</span>
                  <span v-if="modelForm.type=='DIAOBOBIN'">调拨入库</span>
                  <span v-if="modelForm.type=='SHOUHUOIN'">收货入库</span>
                  <span v-if="modelForm.type=='OTHERIN'">其他入库</span>
                </div>
              </div>
              <div class="el-input el-input-group el-input-group--prepend addprepend el-input--medium" v-else >
                <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
                  <span>状态</span>
                </div>
                <el-radio-group class="radio-group" v-model="modelForm.type" >
                  <el-radio v-for="item in types" :label="item.label" :value="item.label" :key="item.label">
                    {{item.value}}</el-radio>
                  <!--<el-radio label="OTHERIN" >其他入库</el-radio>-->
                </el-radio-group>
              </div>


            </el-col>
            <el-col :span="9">
              <el-form-item  prop="storeId" :rules="[]" >
                <div class="el-input el-input-group el-input-group--prepend">
                  <div class="el-input-group__prepend">商品信息库</div>
                  <el-select v-model="modelForm.storeId" @change="storeChange" filterable placeholder="请选择商品信息库" :disabled="isEdit" style="width: 100%">
                    <el-option
                      v-for="item in storeList"
                      :key="item.id"
                      :label="item.name"
                      :disabled="item.state!='NORMAL'"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="no" :rules="[]">
                <el-input type="text" v-model="modelForm.remark" size="medium"
                          auto-complete="off"
                          class="w-100p"
                          :disabled="isEdit"
                          placeholder="请输入备注信息">
                  <template slot="prepend">
                    <el-button>备注</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="">
          <el-form-item class="text-left text-left1">
            <el-button size="medium" type="primary" @click="submitForm('modelForm')"><i class="icon icon-baocun"></i> 保存</el-button>
            <el-button size="medium" type="success" @click="resetForm('modelForm')"><i class="icon icon-tijiao"></i> 提交并审核</el-button>
            <el-button size="medium" type="warning" v-if="modelForm.id"><i class="icon icon-dayin"></i> 打印</el-button>
            <el-button size="medium" type="danger" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
          </el-form-item>
          <el-form-item class="text-left text-left5">
            <el-button type="warning" size="medium"><i class="icon icon-dayin"></i> 打印</el-button>
            <el-button type="danger" size="medium" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
          </el-form-item>
          <div class="orderTable">
          <el-table
            :data="tableData"
            border
            show-summary
            :summary-method="getSummaries"
            style="width: 100%">
            <el-table-column
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              width="80">
              <template  slot-scope="scope">
                                <span class="el-icon-plus" style="cursor: pointer;font-size: 10px;padding-right: 5px"
                                      @click="addColumn(scope.$index)"></span>
                <span class="el-icon-minus" style="cursor: pointer;font-size: 10px;padding-left: 5px"
                      @click="minusColumn(scope.$index)"></span>
              </template>
            </el-table-column>
              <el-table-column
                prop="code"
                label="编号"
                width="150">
                <template  slot-scope="scope">
                  <div style="position: relative">
                    <el-select :class="'coderef_'+scope.$index" :ref="'coderef_'+scope.$index"  v-model="scope.row.code" :disabled="isEdit" remote @change="codeChange(scope.$index)"   :remote-method="remoteMethod"
                               filterable="" placeholder="编号/条码/名称/简码" @keyup.enter.native="codeEnter($event,scope.$index)" @focus="codeFocus">
                      <el-option :disabled="true" value="0000" style="background-color: #409EFF;color: #fff;">
                        <div style="width:600px;" >
                          <el-row>
                            <el-col :span="4">编号</el-col>
                            <el-col :span="5">条码</el-col>
                            <el-col :span="9">名称</el-col>
                            <el-col :span="3">库存单位</el-col>
                            <el-col :span="3">采购规格</el-col>
                          </el-row>
                        </div>
                      </el-option>
                      <el-option v-for="(item,index) in material" :disabled="(item.state && item.state.key!='NORMAL')" :key="index"
                                 :label="item.code" :value="item.no" >
                        <div style="width:600px;border-bottom:1px solid #c0c0c0;padding:5px 0px">
                          <!--{{item.value}}[{{item.purchaseUnit}}]-->
                          <el-row>
                            <el-col :span="4"><span v-if="item.no">{{item.no}}</span><span v-else>-</span></el-col>
                            <el-col :span="5"><span v-if="item.goodcode">{{item.goodcode}}</span><span v-else>-</span></el-col>
                            <el-col :span="9"><span v-if="item.value">{{item.value}}</span><span v-else>-</span></el-col>
                            <el-col :span="3"><span v-if="item.unit">{{item.unit}}</span><span v-else>-</span></el-col>
                            <el-col :span="3"><span v-if="item.purchaseSpec">{{item.purchaseSpec}}</span><span v-else>-</span></el-col>
                          </el-row>
                        </div>
                      </el-option>
                    </el-select>
                    <span class="el-icon-more" @click="handleIconClick(scope.$index)"
                          style="cursor: pointer;font-size: 10px;padding-right: 5px; position: absolute;right: 10px;top: 40%"></span>
                  </div>
                </template>
              </el-table-column>
            <el-table-column
              prop="goodcode"
              label="条码">
              <template  slot-scope="scope">
                <el-tooltip class="item" effect="light" placement="bottom-start" v-if="scope.row.goodcodes && scope.row.goodcodes.length>1">
                  <div slot="content">所选品项含有多个条码:<br/>
                    <div v-for="(item,index) in scope.row.goodcodes">
                      <span>{{index+1}}、{{item}}</span>
                    </div>
                  </div>
                  <el-button  type="text" style="padding-top: 0; padding-bottom: 0">{{scope.row.goodcode}}</el-button>
                </el-tooltip>
                <span v-else>{{scope.row.goodcode}}</span><br />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="名称"
            >
            </el-table-column>
            <el-table-column
              prop="spec"
              label="规格型号"
            >
            </el-table-column>
            <el-table-column
              prop="purchaseSpec"
              label="采购规格"
              width="80">
            </el-table-column>
            <el-table-column
              prop="unitName"
              label="采购单位"
              width="80">
            </el-table-column>
            <el-table-column
              prop="count"
              label="采购数量"
              width="100">
              <template  slot-scope="scope">
                <el-input v-model="scope.row.count" :disabled="isEdit"
                          @blur="priceValidate(scope.row,'count')" placeholder="0.00" @focus="printNum()"
                          :class="'focus_input_'+scope.$index" @keyup.enter.native="nextFocus(scope.$index,'price_focus_')"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="price"
              label="采购单价"
              width="100">
              <template  slot-scope="scope">
                <el-input v-model="scope.row.price" :disabled="isEdit" :class="'price_focus_'+scope.$index" @keyup.enter.native="nextFocus(scope.$index,'sum_price_focus_')"
                          @blur="priceValidate(scope.row,'price')" placeholder="0.00"  @focus="printNum()"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="money"
              label="采购金额"
              width="100">
              <template  slot-scope="scope">
                <el-input v-model="scope.row.money" :disabled="isEdit" :class="'sum_price_focus_'+scope.$index" @keyup.enter.native="nextFocus(scope.$index,'remark_focus_')"
                          @blur="priceValidate(scope.row,'money')" placeholder="0.00"  @focus="printNum()"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="unit"
              label="库存单位"
              width="80">
            </el-table-column>
            <el-table-column
              prop="storageCount"
              label="入库数量"
              width="80">
              <template  slot-scope="scope">
                <span>{{scope.row.storageCount | money}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="storagePrice"
              label="入库单价"
              width="100">
              <template  slot-scope="scope">
                <span>{{scope.row.storagePrice | money}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="storageTotal"
              label="入库金额"
              width="100">
              <template  slot-scope="scope">
                <span>{{scope.row.storageTotal | money}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="memo"
              label="备注">
              <template  slot-scope="scope">
                <el-input :class="'remark_focus_'+scope.$index" @keyup.enter.native="nextFocus(scope.$index,'')" v-model="scope.row.memo" :disabled="isEdit" placeholder=""></el-input>
              </template>
            </el-table-column>
          </el-table>
          </div>
          <el-row style="margin-top: 15px" class="text-left" v-if="modelForm.supplierId">
            <el-col :span="8">
              <el-input type="text" style="width:80%" size="medium" :disabled="true" v-model="sumOrderPrice" auto-complete="off" placeholder="请输入本单优惠金额">
                <template slot="prepend">
                  <el-button>总金额</el-button>
                </template>
              </el-input>
            </el-col>
            <el-col :span="8">
              <el-input type="text" style="width:80%"  size="medium" v-model="modelForm.giftAmount" :disabled="isEdit" auto-complete="off"   @focus="printNum()"   @blur="isDouble(modelForm,'giftAmount');calcPrice()"
                        placeholder="优惠金额">
                <template slot="prepend">
                  <el-button>优惠金额</el-button>
                </template>
              </el-input>
            </el-col>
            <el-col :span="8">
              <el-input type="text" style="width:80%"  size="medium" v-model="modelForm.payAmount" :disabled="isEdit" auto-complete="off"  @focus="printNum()"  @blur="isDouble(modelForm,'payAmount');calcPrice()"
                        placeholder="实付款金额">
                <template slot="prepend">
                  <el-button>实付款金额</el-button>
                </template>
              </el-input>
            </el-col>
          </el-row>

        </div>
      </el-form>
    </div>
    <materials-select :isShow="dialogTableVisible" :storeId="modelForm.storeId" v-on:pushData="getData" v-on:closeDialog="dialogTableVisible=false"></materials-select>
  </div>
</template>
<script>
  import materialsSelect from "@/components/materialsSelect.vue"
  //注意路径
  export default {
    data() {
      return {
        sumOrderPrice:0,
        type:"",
        types:[{label:"STOREIN",value:"采购入库"},{label:"OTHERIN",value:"其它入库"}],
        dialogTableVisible: false,
        isEdit: false,
        storeInType: "STOREIN",
        tableData: [{
          id: "",
          code: '',
          name: '',
          goodsSpec: '',
          purchaseSpec: '',
          purchaseUnit: '',
          count: '0',
          price: '0.00',
          money: '0.00',
          unit: "",
          storageCount: "0",
          storagePrice: "0.00",
          storageTotal:"0.00",
          memo: '',
        }],
        modelForm: {
          type: "STOREIN",
          id: "",
          inTime: ""
        },
        pageSizeSet:window.pageSizes,
        pageSize:window.pageSize,
        pageTotal: 10,
        material: [],
        supplier: "",
        content: "",
        warehouse: "",
        suppliers: [],
        warehouses: [],
        restaurants: [],
        timeout: null,
        gridData: [],
        itemActive: 0,
        data: [],
        selectRow: [],
        inputText: "",
        defaultProps: {
          children: 'children',
          label: 'label'
        },
      storeList:[], //商品原料库
        query:"",
       loading:false,
      };
    },
    components: {
      materialsSelect
    },
    created() {
      window.this = this;

     this.initData();
    },
    mounted() {

      if (this.$route.query.type != null && this.$route.query.type != "") {
        if (this.$route.query.type == "5") {//5 说明是查看
          $("input").attr("disabled", true);
          $(".text-left1").css("display", "none");
          $(".text-left5").css("display", "block");
          this.isEdit = true;
        }

      }
    },
    methods: {
      calcPrice(){
        var sum=Number(this.sumOrderPrice);
        var discount=Number(this.modelForm.giftAmount);
        var recharge=Number(this.modelForm.payAmount);
        if(discount>sum){
          this.$message.error("优惠金额不能大于总金额");
          this.modelForm.giftAmount=0.00;
          return false;

        }
        if(recharge>sum){
          this.$message.error("实付金额不能大于总金额");
          this.modelForm.payAmount=0.00;
          return false;
        }
        if((discount+recharge)>sum){
          this.$message.error("输入金额有误，请重新核对");
          this.modelForm.giftAmount=0.00;
          this.modelForm.payAmount=0.00;
          return false;
        }
      },
      isDouble(item,key){
        // var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        var isNum=/^\d+(\.{0,1}\d+){0,1}$/
        if(!isNum.test(item[key])){
          item[key]="0.00"
        }else{
          item[key]=item[key]
        }
      },
      codeFocus(){
        this.material=[];
      },
      nextFocus(index,name){
        if(name){
          $("."+name+index+" input").focus();
        }else {
          $(".coderef_"+(index+1)+" input").focus();

        }
      },
      storeChange(){
        this.material = [];
        if(this.tableData && this.tableData.length>0 && this.tableData[0].id !=''){
          this.$confirm('切换商品信息库将清除已选择的物品信息?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.tableData = [{
              id:"",
              code: '',
              name: '',
              goodsSpec: '',
              purchaseSpec: '',
              unitName:'',
              count:'0',
              price:'0.00',
              historyPrice:'',
              money:'0.00',
              memo:'',
            }];
          }).catch(() => {

          });
        }
      },
      codeEnter(e,index){
        if(e && e.target && e.target.value){
          this.$axios.get("materials/materials/getMaterialsByNameOrCode?storeId="+this.modelForm.storeId+"&name="+e.target.value).then(data=>{
            this.loading = false;
            if(data.status==200){
              this.material=data.content.materialList;
              this.$refs['coderef_'+index].blur();
              if(e && this.material.length<=0){
                e.target.select();
                return;
              }
              this.codeForTable(index);
              console.log("333333");
              if(!this.tableData[index+1]){
                this.addColumn(index);
              }
              this.material=[];
              console.log("555555");
              setTimeout(function () {
                $(".focus_input_"+index+" input").focus();
              },300);
            }
          });
        }else {
          return;
        }
      },
      codeForTable(index) {
        if(this.material && this.material.length>0){
          if(this.tableData && this.tableData.length>0){
            for (var m = 0; m < this.tableData.length; m++) {
              if (m!=index && this.material[0].label == this.tableData[m].id) {
                this.$message.info("您本次添加的["+this.tableData[m].code+"]品项含有重复");
                break;
              }
            }
          }
          this.tableData[index].name = this.material[0].name;
          this.tableData[index].id = this.material[0].label;
          this.tableData[index].name = this.material[0].nameValue;
          this.tableData[index].goodcode = this.material[0].goodcode;
          this.tableData[index].goodcodes = this.material[0].goodcodes;
          this.tableData[index].goodcodestrs = this.material[0].codes;
          this.tableData[index].code = this.material[0].no;
          this.tableData[index].purchaseSpec = this.material[0].goodsSpec; //规格型号
          this.tableData[index].spec = this.material[0].purchaseSpec; //采购规格
          this.tableData[index].unitName = this.material[0].purchaseUnit; //采购单位
          this.tableData[index].price = (this.material[0].purchasePrice * 1).toFixed(2);
          this.tableData[index].count = 0;
          this.tableData[index].money = (this.tableData[index].price * this.tableData[index].count).toFixed(2);
          this.tableData[index].purchaseNewPrice = this.material[0].purchaseNewPrice;
          this.tableData[index].purchaseCount = this.material[0].purchaseCount;
        }
        this.material=[];
      },
      codeChange(index) {
        console.log("query :::::::>>>:",this.query);
        for (var i = 0; i < this.material.length; i++) {
          if (this.material[i].no === this.tableData[index].code) {
            this.tableData[index].code = this.material[i].no;
            for (var m = 0; m < this.tableData.length; m++) {
              if (this.material[i].label == this.tableData[m].id) {
                this.$message.info("您本次添加的["+this.tableData[m].code+"]品项含有重复");
                break;
              }
            }
            this.tableData[index].id = this.material[i].label;
            this.tableData[index].name = this.material[i].nameValue;
            this.tableData[index].materialId = this.material[i].materialId;
            this.tableData[index].code = this.material[i].no;
            this.tableData[index].spec = this.material[i].goodsSpec;
            this.tableData[index].unitName = this.material[i].purchaseUnit;
            this.tableData[index].purchaseSpec = this.material[i].purchaseSpec;
            this.tableData[index].price = (this.material[i].purchasePrice * 1).toFixed(2);
            this.tableData[index].purchaseCount = this.material[i].purchaseCount;
            this.tableData[index].count = 0;
            this.tableData[index].money = (this.tableData[index].price * this.tableData[index].count).toFixed(2);
            this.tableData[index].purchaseNewPrice = this.material[i].purchaseNewPrice;
            this.tableData[index].state = this.material[i].state;
            this.tableData[index].purchaseCount = this.material[i].purchaseCount;
            this.tableData[index].unit = this.material[i].unit;
            this.tableData[index].storagePrice = this.material[i].purchaseNewPrice/this.material[i].purchaseCount;





            if(this.material[i].codes && this.material[i].codes!=''){
              if(this.material[i].codes.indexOf(","+this.query+",")!=-1){
                this.tableData[index].goodcode = this.query;
              }else {
                this.tableData[index].goodcode = this.material[i].codes.substring(1,this.material[i].codes.indexOf(",",2));
              }
              this.material[i].codes = this.material[i].codes.substring(1,this.material[i].codes.length-2);
              if(this.material[i].codes!=''){
                this.tableData[index].goodcodes = this.material[i].codes.split(",");
              }
            }else{
              this.tableData[index].goodcode="";
              this.tableData[index].goodcodes=[];
            }
            this.tableData[index].goodcodestrs = this.material[i].codes;
            this.material = [];
            this.codeEnter("",index);
            break;
          }
        }
      },
      remoteMethod(query) {
        if(!this.modelForm.storeId){
          this.$message({
            message: '请选择商品信息库',
            type: 'warning'
          });
          return;
        }
        this.query = query;
        if (query != '') {
          this.loading = true;
          this.getMaterialForQuery(query);
        } else {
          this.material=[];
        }
      },
      getMaterialForQuery(query){
        if(query){
          this.$axios.get("materials/materials/getMaterialsByNameOrCode?storeId="+this.modelForm.storeId+"&name="+query).then(data=>{
            this.loading = false;
            if(data.status==200){
              if(data.content.materialList && data.content.materialList.length>0){
                this.material=data.content.materialList;
              }else {
                this.material=data.content.materialList;
              }
            }
          });
        }

      },
      getData(data){
        if(!this.material){
          this.material = [];
        }
        var a=0;
        for(var i=0;i<data.length;i++){
          a=0;
          for(let s=0;s<this.material.length;s++){
            if(this.material[s].id==data[i].id){
              a++;
            }
          }
          if(a<=0){
            data[i].value="["+data[i].no+"]"+data[i].name;
            this.material.push(data[i]);
          }
          this.tableData.push({

            id:data[i].id,
            materialId:data[i].materialId,
            code:data[i].no,
            name:data[i].name,
            spec:data[i].goodsSpec,
            purchaseSpec:data[i].purchaseSpec,
            unitName:data[i].purchaseUnit,
            count: '0',
            price:  data[i].purchasePrice.toFixed(2),
            purchasePrice: data[i].purchasePrice,
            purchaseNewPrice: data[i].purchaseNewPrice,
            money: '0.00',
            memo: '',
            value:"["+data[i].no+"]"+data[i].name,
            unit:data[i].unit,
            storagePrice:data[i].purchaseNewPrice*1/data[i].purchaseCount,
            storageCount:"0.00",
            storageTotal:"0.00",
            purchaseCount:data[i].purchaseCount,
            goodcode:data[i].goodcode,
            goodcodes:data[i].goodcodes,
            goodcodestrs:data[i].goodcodestrs
          });
        }
        for(var i=0;i<this.tableData.length;i++){
          if(this.tableData[i].purchaseNewPrice==null || this.tableData[i].purchaseNewPrice==''){
            this.tableData[i].purchaseNewPrice=this.tableData[i].purchasePrice;
          }
          if(this.tableData[i].id==''){
            this.tableData.splice(i,1);
          }
        }
        this.material = [];
        this.dialogTableVisible=false;
      },
      //页面第一次进来获取表单需要的数据
      initData() {
        var id = this.$route.query.id;
        var query = "";
        if (id != null && id != "") {
          query = "?id=" + id;
          this.modelForm.id = id;
        }

        this.$axios.get("stores/storeInOrders/create" + query).then(data=> {
          if (data.status == 200) {
            var value = data.content;
            if(id==''|| id==null){
              value.storeInOrder.type=this.types[0].label;
            }

            this.modelForm = value.storeInOrder;
            this.suppliers = value.suppliers;
            this.warehouses = value.warehouses;
            this.storeList = value.storeList;
            this.modelForm.inTime = this.moment(new Date()).format("YYYY-MM-DD");
            if (id != null && id != "") {
              this.material=value.materials;
              this.modelForm.supplier = value.storeInOrder.supplierId;
              this.modelForm.address = value.storeInOrder.address;
              this.modelForm.remark = value.storeInOrder.remark;
              for (var i = 0; i < value.detailList.length; i++) {
              for(var j=0;j<value.materials.length;j++){
                  if(value.detailList[i].specId==value.materials[j].label){
                    value.detailList[i].purchaseNewPrice=value.materials[j].purchaseNewPrice;
                    value.detailList[i].purchaseCount=value.materials[j].purchaseCount;
                    // value.detailList[i].materialId=value.materials[j].materialId;
                  }
                }

//                value.detailList[i].code = value.detailList[i].no;
                if(value.detailList[i].price){
                  value.detailList[i].price = (value.detailList[i].price * 1).toFixed(2);
                }else{
                  value.detailList[i].price=0;
                }
                if(value.detailList[i].count){
                  value.detailList[i].count = (value.detailList[i].count * 1);
                }else{
                  value.detailList[i].count=0;
                }
                if(value.detailList[i].total){
                  value.detailList[i].money = value.detailList[i].total.toFixed(2);
                }else{
                  value.detailList[i].money=0;
                }
                value.detailList[i].unitName = value.detailList[i].purchaseUnit;
                value.detailList[i].purchaseSpec = value.detailList[i].purchaseSpec;
                value.detailList[i].spec = value.detailList[i].spec;
                value.detailList[i].id = value.detailList[i].specId ;
                value.detailList[i].name = value.detailList[i].name ;
                value.detailList[i].memo = value.detailList[i].remark ;
                value.detailList[i].storagePrice=value.detailList[i].storagePrice*1;
                value.detailList[i].storageCount=value.detailList[i].storageCount*1;
               value.detailList[i].storageTotal=value.detailList[i].storageTotal*1;
                // value.detailList[i].purchaseCount = value.detailList[i].purchaseCount ;
                value.detailList[i].purchaseNewPrice = value.detailList[i].historyPrice ;
                if(value.detailList[i].code && value.detailList[i].code!=''){
                  if(value.detailList[i].code.indexOf(","+this.query+",")!=-1){
                    value.detailList[i].goodcode = this.query;
                  }else {
                    value.detailList[i].goodcode = value.detailList[i].code.substring(1,value.detailList[i].code.indexOf(",",2));
                  }
                  value.detailList[i].code = value.detailList[i].code.substring(1,value.detailList[i].code.length-2);
                  if(value.detailList[i].code!=''){
                    value.detailList[i].goodcodes = value.detailList[i].code.split(",");
                  }
                }else{
                  value.detailList[i].goodcode="";
                  value.detailList[i].goodcodes=[];
                }
                value.detailList[i].goodcodestrs = value.detailList[i].code;
                value.detailList[i].code = value.detailList[i].no;

              }
              this.tableData = value.detailList;
              for(var i=0;i<this.tableData.length;i++){
                this.priceValidate(this.tableData[i],"count");
              }
              this.material=[];
            }
          } else {
            this.$message.error(data.message);
          }
        })
      },
      printNum(){
        event.currentTarget.select();
      },
      handleIconClick(index) {
        if(!this.modelForm.storeId){
          this.$message({
            message: '请选择商品信息库',
            type: 'warning'
          });
          return;
        }

        if (this.isEdit) {
          return;
        }
        this.dialogTableVisible = true;
        this.itemActive = index;

      },
      selectGood(page) {
        this.dialogTableVisible = true;
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.selectGood();
      },
      handleNodeClick(data) {
        var id = data.id;
        this.content = "search.category.id_eq=" + id + "";
        this.selectGood();
      },
      goBack() {
        this.router.go(-1);
      },
      getSummaries(param) {
        const {columns, data} = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if (index == 8 || index == 10 || index == 12 || index == 14) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                if(isNaN(curr)){
                  return 0;
                }
                const value = Number(curr);
                if(index==10 || index==14){
                  if (!isNaN(value)) {
                    return ((prev*1 + curr*1)*1).toFixed(2);
                  } else {
                    return prev;
                  }
                }else{
                  return (prev*1 + curr*1).toFixed(2);
                }
              }, 0);
            } else {
              sums[index] = '0.00';
            }
          }
        });
        console.log(sums);
        this.sumOrderPrice=sums[10];
        return sums;
      },
      submitForm(formName) {
        this.type = 1;
        this.validateData(formName);
      },
      resetForm(formName) {
        this.type = 2;
        this.validateData(formName);
      },
      validateData(fromName) {
        if (this.modelForm.warehouseId == null) {
          this.$message.error("请选择仓库！");
          return;
        }
        // if (this.modelForm.supplierId == null) {
        //   this.$message.error("请选择供应商！");
        //   return;
        // }
        if (this.tableData == null || this.tableData.length == 0) {
          this.$message.error("请添加单据明细！");
          return;
        }
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id == "") {
            if (this.tableData.length == 1) {
              this.$message.error("请添加单据明细！");
              return;
            }
            this.tableData.splice(i, 1);
            i--;
          }
          if(this.tableData[i].count==0){
            this.$message.error("请检查单据，采购数量不能为0！");
            return ;
          }
        }

        if (this.$route.query.type == "4") {//5 说明是查看
          this.modelForm.id = "";
        }
        this.$refs[fromName].validate((valid) => {
          if (valid) {
            var data = {};
            data.type=this.type;
            for(let i=0;i<this.suppliers.length;i++){
              if( this.modelForm.supplierId==this.suppliers[i].id){
                this.modelForm.supplierName=this.suppliers[i].name;
              }
            }
            for(let i=0;i<this.warehouses.length;i++){
              if( this.modelForm.warehouseId==this.warehouses[i].id){
                this.modelForm.warehouseName=this.warehouses[i].name;
              }
            }
            data.storeInOrder= this.modelForm;
            var tempData=[];
            for(let i=0;i<this.tableData.length;i++){
              tempData.push({
                specId:this.tableData[i].id,
                materialId:this.tableData[i].materialId,
                no:this.tableData[i].code,
                name:this.tableData[i].name,
                purchaseSpec:this.tableData[i].purchaseSpec,
                purchaseUnit:this.tableData[i].unitName,
                count:this.tableData[i].count,
                price:this.tableData[i].price,
                total:this.tableData[i].money,
                purchaseNewPrice:this.tableData[i].purchaseNewPrice,
                amount:this.tableData[i].money,
                remark:this.tableData[i].memo,
                spec:this.tableData[i].spec,
                unit:this.tableData[i].unit,
                storageUnit:this.tableData[i].unitName,
                storageCount:this.tableData[i].storageCount,
                storagePrice:this.tableData[i].storagePrice,
                storageTotal:this.tableData[i].storageTotal
              })
            }
            data.details = tempData;
            this.$axios.post("stores/storeInOrders/create", data, "json").then(data=> {
              if (data.status == 200) {
                this.$message({
                  message: data.message,
                  type: 'success'
                });
                this.$emit('addSuccess');
                this.router.push({path: "/hqStoreInOrders"});
              } else {
                this.$message.error(data.message);
              }
            })
          } else {
            this.$message.error("请检查输入项");
            return false;
          }
        });
      },
      isNumber(value) {
        if (value===0) {
          return false
        } else {
          return true
        }
      },
      priceValidate(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {

          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }

        console.log(item.count);

        switch (key) {
          case "count":
            if(!isNaN(item.price*1) && !isNaN(item.count*1) ){
              console.log("dddddddd");
              item.money = (item.price * item.count).toFixed(2);
              item.count=(item.count*1).toFixed(2);
              console.log('purchaseCount'+(item.purchaseCount));
              item.storageCount = (item.count * item.purchaseCount).toFixed(2);
              console.log( item.storageCount)
              if( item.storageCount>0 && !isNaN(item.money)){
                console.log("KKKKKKK");
                item.storagePrice = (item.price / item.purchaseCount * 1).toFixed(2);
                item.storageTotal =(item.money*1).toFixed(2);
              }
              console.log("mnnnnnnnnnnnnnn : ",item.count);
            }else{
              console.log("-=======vvvvv :",item.count);
              item.price="0.00";
              item.count=0;
              item.storageCount = 0;
              item.storagePrice ="0.00";
              item.storageTotal ="0.00";
            }
            break;
          case "price":
            if(!isNaN(item.price*1 ) && !isNaN(item.count*1) && !isNaN(item.purchaseCount)){
              console.log("ddggggggggggggg");
              item.price=(item.price*1).toFixed(2);
              item.money = (item.price *item.count).toFixed(2) ;
              item.storageCount = (item.count * item.purchaseCount).toFixed(2);
              if( item.storageCount>0 && !isNaN(item.money)){
                item.storagePrice = (item.price / item.purchaseCount * 1).toFixed(2);
                item.storageTotal =(item.money*1).toFixed(2);
              }
            }else{
              item.price="0.00";
              item.count="0";
              item.purchaseCount="0";
              item.money="0.00";
              item.storageCount = 0;
              item.storagePrice = "0.00";
              item.storageTotal ="0.00";
            }
            break;
          case "money":
            item.money=(item.money*1).toFixed(2);
            if (!isNaN(item.money*1 ) &&  item.count>0 ) {
              item.price = (item.money / item.count).toFixed(2);
              item.storagePrice = (item.price / item.purchaseCount * 1).toFixed(2);
              item.storageTotal =(item.money*1).toFixed(2);
            }else{
              item.storageCount="0";
              item.storagePrice="0.00";
              item.storageTotal="0.00";
            }
            break;
        }
      },
      handleCurrentChange(item) {
        this.currentPage3=item;
        this.selectGood(item);
      },
      inputClick() {
        this.content = "search.code_eq=" + this.inputText;
        this.selectGood("");
      },
      addColumn(index) {
        if (this.isEdit) {
          return;
        }
        this.tableData.splice(index + 1, 0, {
          id: '',
          code: '',
          name: '',
          goodsSpec: '',
          purchaseSpec: '',
          purchaseUnit: '',
          count: '0',
          price: '0.00',
          money: '0.00',
          unit: "",
          stockCount: "0",
          stockPrice: "0.00",
          memo: '',
        })
      },
      minusColumn(index) {
        if (this.isEdit) {
          return;
        }
        if (this.tableData.length > 1) {
          this.tableData.splice(index, 1);
        } else {
          this.$message.info("最少保留一条");
        }
      },
      handleSelect(item, index) {
        console.log(this.tableData[index])
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.indexOf(queryString.toLowerCase()) === 0);
        };
      },
      checkboxInit(row,index){
        if(row.state && row.state.key!="NORMAL"){
          return 0;//不可勾选
        }else{
          return 1;
        }
      },
      chnageGoodState(row, column, cell, event){
        if(row.state && row.state.key!="NORMAL"){
          return;
        }else{
        }
        this.$refs.multipleTable.toggleRowSelection(row);
      },
      handleSelectionChange(val) {
        this.selectRow = val;
      },
      tableClick() {
        this.dialogTableVisible = false;
        console.log(this.selectRow);
        if (this.selectRow != null && this.selectRow.length > 0) {
          for (var i = this.selectRow.length - 1; i >= 0; i--) {
            var isAdd = true;
            for (var m = 0; m < this.tableData.length; m++) {
              if (this.selectRow[i].id == this.tableData[m].id) {
                // isAdd=false;
                this.$message.info("本次添加含有重复原料");
                break;
              }
            }
            if (isAdd) {
              console.log("----------------");
              console.log(this.selectRow[i]);
              this.addColumn(this.itemActive);
              this.tableData[this.itemActive + 1].code = "["+this.selectRow[i].no+"]"+this.selectRow[i].name+"["+this.selectRow[i].purchaseUnit+"]";
              this.tableData[this.itemActive + 1].name = this.selectRow[i].name;
              this.tableData[this.itemActive + 1].id = this.selectRow[i].id;
              this.tableData[this.itemActive + 1].goodsSpec = this.selectRow[i].goodsSpec;
              this.tableData[this.itemActive + 1].purchaseUnit = this.selectRow[i].purchaseUnit;
              this.tableData[this.itemActive + 1].purchaseSpec = this.selectRow[i].purchaseSpec;
              this.tableData[this.itemActive + 1].price = this.selectRow[i].purchasePrice;
              this.tableData[this.itemActive + 1].purchaseCount = this.selectRow[i].purchaseCount;
              this.tableData[this.itemActive + 1].storageCount = "0";
              this.tableData[this.itemActive + 1].storagePrice = "0.00";
              this.tableData[this.itemActive + 1].storageTotal = "0.00";
              this.tableData[this.itemActive + 1].unit = this.selectRow[i].unit;
            }
          }
          if (this.tableData[this.itemActive].id == "") {
            this.tableData.splice(this.itemActive, 1);
          }

        }
      }

    },

  }
</script>
<style scoped>
  .el-form-item {
    margin-bottom: 10px !important;
  }

  .el-table tr {
    border-bottom: 1px solid #dfe6ec !important;
  }

  .text-left5 {
    display: none;
  }
</style>
